<?php

require_once(WSB_XTENSION_PATH .'login/forms/Login.php');

class Login_IndexController extends WSB_Xtension_Static
{

	public function init()
	{
		$this->initTranslate();
	}

	public function indexAction()
	{
		$request = $this->getRequest();
		$configuration = $this->getConfiguration();
		$useEmailAsUsername = isset($configuration->useEmailAsUsername) ? (bool)$configuration->useEmailAsUsername : false;

		// Cookie Test
		$cookiesEnabled = true;
		if($request->isPost()) {
			if(!is_array($_COOKIE) || (count($_COOKIE) == 0)) {
				$cookiesEnabled = false;
			}
		}
		$this->assignToView('cookiesEnabled', $cookiesEnabled);

		// Eingeloggt
		$auth = WSB_Auth_Frontend::getInstance();
		if($auth->hasIdentity()) {
			$this->assignToView('feuser', $auth->getIdentity());
			$this->assignToView('feuser', $auth->getIdentity());
			$this->renderView('index/authenticated.phtml');
		} else {

			$buttonClicked = ($request->getPost('btnLogin') != '')	// Button
			 || ($request->getPost('btnLogin_x') != '')				// Image button
			 || ($request->getPost('btnLogin_y') != '');			// Image button

			$form = new Login_Form_Login();
			$form->setUseEmailAsUsername($useEmailAsUsername);
			$form->addRequestHiddenElement($request->get('redirect'));
			if($request->isPost() && $buttonClicked) {
				 if($form->isValid($request->getPost())) {
				 	if(!$form->isErrors()) {
				 		if($form->useEmailAsUsername()) {
							$this->assignToView('errors', array($this->translate('loginInvalidEmailOrPassword')));
				 		} else {
							$this->assignToView('errors', array($this->translate('loginInvalidUsernameOrPassword')));
				 		}
				 	}
					// Der eigentlich Login ist in WSB_Frontend implementiert
				 }
			}
			$this->assignToView('form', $form);
			$this->renderView('index/form.phtml');
		}

	}

}
